package io.renren.modules.creditWarning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.creditWarning.dao.CreditApplicationDao;
import io.renren.modules.creditWarning.dto.*;
import io.renren.modules.creditWarning.entity.CreditApplicationEntity;
import io.renren.modules.creditWarning.service.BonusPointsTypeService;
import io.renren.modules.creditWarning.service.CreditApplicationService;
import io.renren.modules.creditWarning.service.UserCreditService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.service.SysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 加分申请表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-05-12
 */
@Service
public class CreditApplicationServiceImpl extends CrudServiceImpl<CreditApplicationDao, CreditApplicationEntity, CreditApplicationDTO> implements CreditApplicationService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private BonusPointsTypeService bonusPointsTypeService;

    @Autowired
    private UserCreditService userCreditService;

    @Override
    public QueryWrapper<CreditApplicationEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String keyWord = (String)params.get("keyWord");
        String status = (String)params.get("status");
        String bonusPointsTypeId = (String)params.get("bonusPointsTypeId");

        QueryWrapper<CreditApplicationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(status), "status", status);
        wrapper.eq(StringUtils.isNotBlank(bonusPointsTypeId), "bonus_points_type_id", bonusPointsTypeId);
        if (StringUtils.isNotBlank(keyWord)) {
            List<SysUserDTO> userDtoList = sysUserService.getByName(keyWord);
            if (CollectionUtils.isNotEmpty(userDtoList)) {
                wrapper.in("creator", userDtoList.stream().map(SysUserDTO::getId).collect(Collectors.toList()));
            } else {
                return null;
            }
        }
        return wrapper;
    }


    @Override
    public PageData<CreditApplicationDTO> getPage(Map<String, Object> params) {
        if (this.getWrapper(params) == null) {
            return new PageData<CreditApplicationDTO>(new ArrayList<CreditApplicationDTO>(), 0);
        }
        PageData<CreditApplicationDTO> page = this.page(params);
        page.getList().forEach(e -> {
            if (StringUtils.isNotBlank(e.getImgUrlList())) {
                e.setImgUrlLists(Arrays.asList(e.getImgUrlList().split(",")));
                e.setIndexImgUrl(e.getImgUrlLists().get(0));
            }
            BonusPointsTypeDTO bonusPointsTypeDto = bonusPointsTypeService.get(e.getBonusPointsTypeId());
            e.setBonusPointsTypeTitle(bonusPointsTypeDto == null ? "" : bonusPointsTypeDto.getTitle());
            e.setBonusPointsTypeCreditNum(bonusPointsTypeDto == null ? new BigDecimal("0.00") : bonusPointsTypeDto.getCreditNum());
            SysUserDTO creatorDto = sysUserService.get(e.getCreator());
            e.setCreatorName(creatorDto == null ? "" : creatorDto.getUsername());
        });
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCreditApplication(CreditApplicationDTO dto) {
        if (dto.getStatus() == 1) {
            UserCreditDTO userCreditDTO = userCreditService.getByUserId(dto.getCreator());
            if (userCreditDTO != null) {
                // 获取类型的分数
                BonusPointsTypeDTO bonusPointsTypeDto = bonusPointsTypeService.get(dto.getBonusPointsTypeId());
                BigDecimal creditNum = bonusPointsTypeDto.getCreditNum();
                // 分数汇总
                userCreditDTO.setCreditNum(userCreditDTO.getCreditNum().add(creditNum));
                userCreditService.update(userCreditDTO);
            }
        }
        this.update(dto);
    }

    @Override
    public List<CreditApplicationDTO> getList(Map<String, Object> params) {
        // 获取当前的报名人
        Long userId = SecurityUser.getUserId();
        List<CreditApplicationDTO> list = this.list(params);
        list = list.stream().filter(e -> e.getCreator().compareTo(userId) == 0).collect(Collectors.toList());
        list.forEach(e -> {
            BonusPointsTypeDTO bonusPointsTypeDTO = bonusPointsTypeService.get(e.getBonusPointsTypeId());
            e.setBonusPointsTypeTitle(bonusPointsTypeDTO == null ? "" : bonusPointsTypeDTO.getTitle());
            e.setBonusPointsTypeCreditNum(bonusPointsTypeDTO == null ? new BigDecimal("0.00") : bonusPointsTypeDTO.getCreditNum());
            SysUserDTO creatorDto = sysUserService.get(e.getCreator());
            e.setCreatorName(creatorDto == null ? "" : creatorDto.getUsername());
            if (StringUtils.isNotBlank(e.getImgUrlList())) {
                e.setImgUrlLists(Arrays.asList(e.getImgUrlList().split(",")));
                e.setIndexImgUrl(e.getImgUrlLists().get(0));
            }
        });
        return list;
    }

    @Override
    public void saveCreditApplication(CreditApplicationDTO dto) {
        if (CollectionUtils.isNotEmpty(dto.getImgUrlLists())) {
            dto.setImgUrlList(StringUtils.join(dto.getImgUrlLists(), ","));
        }
        this.save(dto);
    }
}